package com.zdy.boot.upload.core.job.handler;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.lang.Assert;
import com.zdy.boot.upload.core.job.enums.JobDataKeyEnum;
import lombok.extern.slf4j.Slf4j;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.PersistJobDataAfterExecution;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.quartz.QuartzJobBean;

import javax.annotation.Resource;

/**
 * @author sdy
 * @description
 * @date 2025/2/8
 */
@Slf4j
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class JobHandlerInvoker extends QuartzJobBean {

    @Resource
    private ApplicationContext applicationContext;

    @Override
    protected void executeInternal(JobExecutionContext executionContext) throws JobExecutionException {
        // 第一步，获得 Job 数据
        Long jobId = executionContext.getMergedJobDataMap().getLong(JobDataKeyEnum.JOB_ID.name());
        String jobHandlerName = executionContext.getMergedJobDataMap().getString(JobDataKeyEnum.JOB_HANDLER_NAME.name());
        String jobHandlerParam = executionContext.getMergedJobDataMap().getString(JobDataKeyEnum.JOB_HANDLER_PARAM.name());
        int refireCount  = executionContext.getRefireCount();

        log.info("任务开始执行开始：【{}】::【{}】::【{}】::【{}】::【{}】", jobId, DateUtil.now(), jobHandlerName, jobHandlerParam, refireCount + 1);
        // 获得 JobHandler 对象
        JobHandler jobHandler = applicationContext.getBean(jobHandlerName, JobHandler.class);
        Assert.notNull(jobHandler, "JobHandler 不会为空");
        // 执行任务
        String data = null;
        Throwable error = null;
        try {
            data = jobHandler.execute(jobHandlerParam);
            log.info("定时任务执行结果：{}", data);
        } catch (Throwable ex) {
            error = ex;
        }
        String errorMsg = error == null ? "" : ExceptionUtil.getRootCauseMessage(error);
        log.info("任务开始执行结束：【{}】::【{}】", DateUtil.now(), errorMsg);
    }

}
